package com.xiaobaibai.threadPool;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaobaibai.bo.OrderRecent;
import com.xiaobaibai.common.OrderCommon;
import com.xiaobaibai.common.UserCommon;
import com.xiaobaibai.dao.UserInfoDao;
import com.xiaobaibai.entity.*;
import com.xiaobaibai.service.*;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.*;

@Component
public class MyThreadPoolUnit {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBargainUserService bargainUserService;

    @Autowired
    private IBargainRecordingService bargainRecordingService;

    @Autowired
    private IProductService productService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserInfoDao userInfoDao;

    public static ThreadPoolExecutor threadPoolExecutor=
            new ThreadPoolExecutor(4,10,180,
                    TimeUnit.SECONDS,new LinkedBlockingQueue<>(20),new ThreadPoolExecutor.AbortPolicy());

    //异步存入浏览记录
    public void setFavoritesRedis(String key,String value){
        threadPoolExecutor.execute(()-> {
            stringRedisTemplate.opsForSet().add(UserCommon.favorites + key, value);
            //定时清理时间,不要每次都更新缓存->算了就24小时失效
            stringRedisTemplate.expire(UserCommon.favorites+key,24,TimeUnit.HOURS);
        });
    }

    public void bargainHelpUser(Integer userId,Integer bargainUserId){
        threadPoolExecutor.execute(()->{
            //开始砍价
            //检验是否为新用户
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.select("user_id","user_name","user_image","user_create_time");
            queryWrapper.eq("user_id",userId);
            User user = userService.getOne(queryWrapper);
            boolean flag=false;
            if(DateUtils.addDays(user.getUserCreateTime(),24).getTime()>new Date().getTime())
                flag=true;//新用户
            //先查出进度
            QueryWrapper<BargainUser> q2=new QueryWrapper<>();
            q2.eq("id",bargainUserId);
            q2.select("id","bargain_unit","bargain_new_unit","bargain_progress");
            BargainUser bargainUser = bargainUserService.getOne(q2);
            Integer unit=flag?bargainUser.getBargainNewUnit():bargainUser.getBargainUnit();//获取砍价单位
            double d = RandomUtils.nextDouble(0.6, 1.4);//左闭右开 0.6~0.13
            String format = String.format("%.2f", d * unit);
            double result = Double.valueOf(format);
            String s = String.format("%.2f", bargainUser.getBargainProgress()+result);
            double newProgress=Double.valueOf(s);
            bargainUser.setBargainProgress(newProgress);
            double sum=bargainUser.getBargainProgress();
            if(sum>=100)
                bargainUser.setStatus(2);//设置为砍价成功
            //保存砍价
            bargainUserService.updateById(bargainUser);
            //保存砍价记录
            BargainRecording bargainRecording=new BargainRecording();
            bargainRecording.setHelpUserId(user.getUserId());//帮砍用户
            bargainRecording.setHelpUserImage(user.getUserImage());
            bargainRecording.setBargainUserId(bargainUserId);//对应被砍用户
            bargainRecording.setHelpUserName(user.getUserName());
            bargainRecording.setHelpUnit(result);
            bargainRecordingService.save(bargainRecording);
        });
    }

    //最近订单
    public void recentOrder(Integer productId, Integer userId){
        //最近订单
        threadPoolExecutor.execute(()->{
            //最近订单
            QueryWrapper<User> q1=new QueryWrapper<>();
            q1.select("user_name","user_image");
            q1.eq("user_id",userId);
            User user = userService.getOne(q1);
            Product product = productService.getProductById(productId);
            OrderRecent orderRecent=new OrderRecent();
            orderRecent.setUserName(user.getUserName());
            orderRecent.setProductId(productId);
            orderRecent.setUserImage(user.getUserImage());
            orderRecent.setProductName(product.getProductName()+"等等");
            orderRecent.setCreateTime(new Date());
            redisTemplate.opsForList().leftPush(OrderCommon.recentOrder,orderRecent);
        });
    }

    //异步增加积分
    public void addUserInfoIntegral(Integer userId,Integer count){
        threadPoolExecutor.execute(()->{
            userInfoDao.addUserInfoIntegral(userId,count);
        });
    }

}
